package com.dongxing.concyrrency.chapter1;

import java.util.concurrent.TimeUnit;

/**
 * @author XavierDong
 **/
public class TryConcurrency {

    public static void main(String[] args) {

//        // 只是java的实例，只有启动后，才会是一个线程
//        Thread t1 = new Thread("Custom-Thread") {
//            @Override
//            public void run() {
//                for (int i = 0; i < 100; i++) {
//                    println("Task 1=>" + i);
//                    try {
//                        TimeUnit.MILLISECONDS.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        };
//        t1.start();
//
//
//        for (int j = 0; j < 100; j++) {
//            println("Task 2=>" + j);
//        }


/*
        for (int i = 0; i < 100; i++) {
            println("Task 1=>" + i);

        }

        for (int j = 0; j < 100; j++) {
            println("Task j=>" + j);
        }
*/
//        try {
//            TimeUnit.SECONDS.sleep(300);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }


//        readFromDataBase();
//        writeDataToFile();

        // 边读数据库边写文件
        new Thread("READ-Thread") {

            @Override
            public void run() {
                println(Thread.currentThread().getName());
                readFromDataBase();
            }
        }.start();

        new Thread("WRITE-Thread") {

            @Override
            public void run() {
                writeDataToFile();
            }
        }.start();

    }


    private static void readFromDataBase() {
        // read data from database and handle it.
        try {
            println("Begin read data from db.");
            TimeUnit.SECONDS.sleep(10);
            println("Read data done and start handle it.");
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }

        println("The data handle finish and successfully");
    }

    private static void writeDataToFile() {
        try {
            println("Begin write data from db.");
            TimeUnit.SECONDS.sleep(20);
            println("Write data done and start handle it.");
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }

        println("The data handle finish and successfully");
    }


    private static void println(final String message) {
        System.out.println(message);

    }

}
